{% extends 'index.html' %}
{% block ace-content %}
<!-- ACE Editor -->   
<script src="http://cdn.bootcss.com/ace/1.2.4/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-language_tools.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/ext-old_ie.js"></script>
<script src="http://cdn.bootcss.com/ace/1.2.4/theme-monokai.js"></script> 
<link href="/static/dist/css/bootstrap-multiselect.css" rel="stylesheet">
<script src="/static/dist/js/bootstrap-multiselect.js"></script>
<script type="text/javascript" src="/static/dist/js/bootstrap-notify.js"></script>
<link href="/static/dist/css/fileinput.css" media="all" rel="stylesheet" type="text/css" />
<script src="/static/dist/js/fileinput.js" type="text/javascript"></script>
<style type="text/css"> 
	td.details-control {
	    background: url('/static/img/details_open.png') no-repeat center center;
	    cursor: pointer;
	}
	tr.shown td.details-control {
	    background: url('/static/img/details_close.png') no-repeat center center;
	} 
	#compile-editor {
		/* position: absolute; */
	width: 100%;
	height: 400px;
   }		
</style>	
{% endblock %}
{% block page-content %}

<div id="page-wrapper">
            <div class="row">
                <div class="col-lg-12">
                    <h1 class="page-header"><i class="fa fa-university"></i> 动态资产组管理</h1>
                </div>
                <!-- /.col-lg-12 -->
            </div>  
            <div class="row">	
				 <div class="col-lg-12" id="add_inventory" style="display:none;">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <i class="fa  fa-rss"></i> 动态资产
                        </div>
                        <!-- /.panel-heading -->
                        <div class="panel-body">
                            <!-- Nav tabs -->
                            <ul class="nav nav-tabs">
                                <li class="active"><a href="#group" data-toggle="tab"><i class="fa fa-cubes"></i> 资产组</a>
                                </li>
                                <li><a href="#host" data-toggle="tab"><i class="fa fa-tasks"></i> 主机变量</a>
                                </li>
                            </ul>

                            <!-- Tab panes -->
                            <div class="tab-content">
                                <div class="tab-pane fade in active" id="group">
	                                <br><br>
									<div class="col-lg-6">
										
										<legend>
											<i class="fa  fa-paper-plane"></i> 动态资产组
										</legend>
										<form role="form" method="post" id="inventory" enctype="multipart/form-data">
											{% csrf_token %}
											<div class="form-group">
			 									<label><font color='red'>* </font>资产组名称<i class="fa fa-info-circle" data-toggle="tooltip" title="名称"></i></label>
												<input class="form-control" rows="3" id="inventory_name" value=""></input>
											</div>								
											<div class="form-group">
			 									<label><font color='red'>* </font>功能描述<i class="fa fa-info-circle" data-toggle="tooltip" title="说明用途"></i></label>
												<textarea class="form-control" rows="3" id="inventory_desc"></textarea>
											</div>																						
											<lable id="auditContol"><button type="button" class="btn btn-default" onclick="addInventory(this)" >添加</button></lable>
											<button type="reset" class="btn btn-default">撤销</button>
										</form>
									</div>
								<!-- /.col-lg-6 (nested) -->
									<div class="hr hr32 hr-dotted"></div>
									<div class="col-lg-6">
										<legend>
											<i class="fa  fa-paper-plane-o"></i> 组成员
										</legend>  
										<form role="form" method="post" id="inventory_group" enctype="multipart/form-data">
										<div class="form-group" >			 		             
											<label><font color='red'>* </font>选择资产组</label>	
											<select class="form-control" name="inventory" id="inventoryIds">
												{% for ds in inventoryList %}
													<option name="inventory" value="{{ds.id}}">{{ds.name}}</option>
												{% endfor %}	
											</select>		
										</div>									
										<div class="form-group">
												<label><font color='red'>* </font>组名称<i class="fa fa-info-circle" data-toggle="tooltip" title="资产组名称(请使用字母表示)"></i></label>
											<input class="form-control" id="group_name" name="group_name" value=""></input>
										</div>								
										<div class="form-group" >			 		             
											<label><font color='red'>* </font>添加主机</label>	
			                                 <select multiple name="ansible_server"  id="server_list" required>
			                                 	{% for ds in serverList %}
			                                 		<option name="server" value="{{ds.id}}">{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
			                                 	{% endfor %}
			                                 </select>		
										</div>																																															
				
										<div class="form-group">
											<label>外部变量<i class="fa fa-info-circle" data-toggle="tooltip" title="该组的外部变量"></i></label>
											<div id="compile-editor" class="ace_editor"></div> 
										</div>
											<lable id="auditContol"><button type="button" class="btn btn-default" onclick="addInventoryGroups(this)" >添加</button></lable>
											<button type="reset" class="btn btn-default">撤销</button>								
										</form>
									</div>	
                                </div>
                                <div class="tab-pane fade" id="host">
                     				<br><br>
									<div class="col-lg-6">
										
										<legend>
											<i class="fa  fa-paper-plane"></i> 选择主机
										</legend>
										<form role="form" method="post" id="add_host_vars">
											{% csrf_token %}
											<div class="form-group" >			 		             
												<label><font color='red'>* </font>选择主机</label>	
				                                 <select class="selectpicker" data-live-search="true"  data-size="5" name="ansible_server"  data-width="100%" id="host_list" required>
				                                 		<option name="server" value="" selected="selected">选择一个主机进行配置</option>
				                                 	{% for ds in serverList %}
				                                 		<option name="server" value="{{ds.id}}">{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
				                                 	{% endfor %}
				                                 </select>	
											</div>	
											<div class="form-group" >
												 <label><font color='red'>* </font>主机变量<i class="fa fa-info-circle" data-toggle="tooltip" title="字典类型"></i></label>
												 <textarea class="form-control" rows="10" name="host_vars" id="host_vars"></textarea>												
											</div>																					
											<lable id="auditContol"><button type="button" class="btn btn-default" id="addHostVars" >添加</button></lable>
											<button type="reset" class="btn btn-default">撤销</button>
									</div>
                                </div>
                            </div>
                        </div>
                        <!-- /.panel-body -->
                    </div>				            
				</div>            			 					           
                 <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            	<i class="fa  fa-paper-plane-o  "></i> 资产组列表
                        </div>
                        <!-- /.panel-heading -->
                        <div class="panel-body">
                        	<div>
                        		<button type="button" class="btn btn-xs btn-default" id="add_inventory_button"><i class="glyphicon glyphicon-plus"></i></button>
                        	</div>
							<table  width="100%" class="table table-striped table-bordered table-hover dataTable no-footer" id="taskTableList">	
						        <thead>
						            <tr>
						                <th class="text-center">详细</th>
						                <th class="text-center">ID</th>
						                <th class="text-center">名称</th>
						                <th class="text-center">用途描述</th>
						                <th class="text-center">添加人</th>
						                <th class="text-center">添加日期</th>
										<th class="text-center">操作</th>
						            </tr>
						        </thead>
						        <tfoot>
						            <tr>
						                <th class="text-center">详细</th>
						                <th class="text-center">ID</th>
						                <th class="text-center">名称</th>
						                <th class="text-center">用途描述</th>
						                <th class="text-center">添加人</th>
						                <th class="text-center">添加日期</th>
										<th class="text-center">操作</th>
						            </tr>
						        </tfoot>													
		                                <tbody>
	                                	{% for ds in inventoryList %}
	                                		<tr>
		                                		<td class="text-center">                                		
		                                		</td>	                                		
		                                		<td class="text-center">
		                                			{{ds.id}}	
		                                		</td>    
		                                		<td class="text-center">
		                                			{{ds.name}}	
		                                		</td>   		                                		                            			
		                                		<td class="text-center">
	                                				{{ds.desc}}
		                                		</td>			                                		                                		
		                                		<td class="text-center">
		                                			{{ds.user}}
		                                		</td>
		                                		<td class="text-center">
		                                			{{ds.create_time|date:"Y/m/d H:i  "}}
		                                		</td>	  		                                			                                		
		                                		<td class="text-center">
													<div class="btn-group">	
															<a href="/apps/inventory/modf/{{ds.id}}/"">
						                                		<button class="btn btn-default btn-xs">					                                					
																	<i class="fa fa-edit bigger-110  bigger-110 icon-only"></i>
																</button>
															</a>
													</div>	
													{% if perms.can_delete_ansible_inventory %}
													<div class="btn-group">	
				                                		<button class="btn btn-default btn-xs"  onclick="deleteAnventoryGroups(this,{{ds.id}})">					                                					
															<i class="fa fa-trash-o  bigger-110  bigger-110 icon-only"></i>
														</button>	
													</div>	
													{% endif %}																																																																																				                                			
		                                		</td>	
	                                		</tr>                                			                                		                                			                                			                                			                                		
	                                	{% endfor %}
	                                </tbody>	                                																				                                   
	                       	</table>	                       	
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
            </div>                    
</div>




<script type="text/javascript"> 

function setAceEditMode(model) {
	var editor = ace.edit("compile-editor");
	require("ace/ext/old_ie");
	var langTools = ace.require("ace/ext/language_tools");
	editor.removeLines();
	editor.setTheme("ace/theme/monokai");
	editor.getSession().setMode("ace/mode/" + model);
	editor.setShowPrintMargin(false);
	editor.setOptions({
	    enableBasicAutocompletion: true,
	    enableSnippets: true,
	    enableLiveAutocompletion: true
	}); 
			 
};
setAceEditMode("sh");


$(document).ready(function() {

    $('#add_inventory_button').click(function(){//点击a标签  
        if($('#add_inventory').is(':hidden')){
        	$('#add_inventory').show();
        }
        else{
        	$('#add_inventory').hide();
        }  
    });	
	
    $('#server_list').multiselect({
        enableClickableOptGroups: true,
        enableCollapsibleOptGroups: true,
        includeSelectAllOption: true,
       	enableFiltering: true,            
    });
    
    $("#host_list").change(function(){
    	id = $('#host_list option:selected').val()
		$.ajax({
				url:'/api/host/vars/'+ id + '/', 
				type:"GET",  //提交类似
			    processData: false,
			    contentType: false,				
				success:function(response){			
					if (response["code"] == 200){
						document.getElementById('host_vars').value=JSON.stringify(response["data"],null,4);
					}
					else {
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
					};
				},
		    	error:function(response){
		    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
		    	}
			});
    });  
    
    $('#addHostVars').click(function(){//点击a标签  
    	console.log($("#host_vars").val())
		$.ajax({
			url:'/api/host/vars/'+ id + '/', 
			type:"POST",  //提交类似
			contentType: "application/json",
		    data: JSON.stringify({
				'host_vars':$("#host_vars").val()
			}),
			success:function(response){			
				if (response["code"] == 200){
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
					
				}
				else {
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				};
			},
	    	error:function(response){
	    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
	    	}
		});    
    });
    
});


function addInventory(obj) {	
	var btnObj = $(obj);
	var required = ["inventory_name","inventory_desc"];
    var formData = new FormData();		
	btnObj.attr('disabled',true);
	var form = document.getElementById('inventory');
		for (var i = 0; i < form.length; ++i) {
			var name = form[i].name;
			var value = form[i].value;	
			idx = $.inArray(name, required);						
			if (idx >= 0 && value.length == 0){
				window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
				btnObj.removeAttr('disabled');
				return false;
			};					
		};			
	    formData.append('inventory_name',$('#inventory_name').val());
	    formData.append('inventory_desc',$('#inventory_desc').val());
		$.ajax({
/* 				dataType: "JSON", */
			url:'/apps/inventory/', //请求地址
			type:"POST",  //提交类似
		    processData: false,
		    contentType: false,				
			data:formData,  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');				
				if (response["code"] == 200){
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
					window.location.reload();
				}
				else {
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				};
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
	    	}
		});	
	}
	
	function deleteAnventoryGroups(obj,id) {
		$.ajax({
			dataType: "JSON",
			url:'/api/inventory/'+ id +'/', //请求地址
			type:"DELETE",  //提交类似
			success:function(response){
				if (response["code"] == 200){
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
					window.location.reload();
				}
				else {
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				};
			}					
		})					
	}

	function addInventoryGroups(obj) {	
		var btnObj = $(obj);
		var required = ["group_name","inventory"];
		var editor = ace.edit("compile-editor");
	    var ext_vars = editor.getSession().getValue(); 	
	    var formData = new FormData();		
		btnObj.attr('disabled',true);
		var form = document.getElementById('inventory_group');
			for (var i = 0; i < form.length; ++i) {
				var name = form[i].name;
				var value = form[i].value;	
				idx = $.inArray(name, required);						
				if (idx >= 0 && value.length == 0){
					window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
					btnObj.removeAttr('disabled');
					return false;
				};					
			};		
			var serverList = new Array();
			$("#server_list option:selected").each(function () {
				serverList.push($(this).val())
			})
			if (serverList.length == 0 ){
				window.wxc.xcConfirm("主机不能为空", window.wxc.xcConfirm.typeEnum.error);
				btnObj.removeAttr('disabled');
				return false;			
			}
			var gid = $('#inventoryIds option:selected').val()
		    formData.append('group_name',$('#group_name').val());
		    formData.append('ids',gid);
		    formData.append('server_list',serverList);
		    formData.append('ext_vars',ext_vars);
			$.ajax({
	/* 				dataType: "JSON", */
				url:'/apps/inventory/groups/' + gid + '/', //请求地址
				type:"POST",  //提交类似
			    processData: false,
			    contentType: false,				
				data:formData,  //提交参数
				success:function(response){
					btnObj.removeAttr('disabled');				
					if (response["code"] == 200){
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.success);
						/* window.location.reload(); */
					}
					else {
						window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
					};
				},
		    	error:function(response){
		    		btnObj.removeAttr('disabled');
		    		window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
		    	}
			});	
		}	
	
	function format ( data ) {
		var serHtml = '';
		serHtml = "<pre>" + JSON.stringify(data["data"],null,4) + "</pre>";			
	    return serHtml;
	}	
	 

	$(document).ready(function() {
	    var table = $('#taskTableList').DataTable( {
/* 	        "ajax": "../ajax/data/objects.txt", */
	        "columns": [
	            {
	                "className":      'details-control',
	                "orderable":      false,
	                "data":           null,
	                "defaultContent": ''
	            },
	            { "data": "id" },
	            { "data": "名称" },
	            { "data": "用途描述" },
	            { "data": "添加人" },
	            { "data": "添加日期"},
	            { "data": "操作" }       
	        ],
	        "order": [[ 0, 'desc' ], [ 5, 'desc' ]]
	    } );    
	    
	    // Add event listener for opening and closing details
	    $('#taskTableList tbody').on('click', 'td.details-control', function () {
	    	var dataList = [];
	        var tr = $(this).closest('tr');
	        var row = table.row( tr );
	        dbId = row.data()["id"];
	        $.ajax({
	            url : "/api/inventory/"+dbId+"/",
	            type : "GET",
	            async : false,
	            dataType : "json",
	            success : function(result) {
	            	dataList = result;
	            }
	        });	        
/* 	    	console.log(dataList); */
	        if ( row.child.isShown() ) {
	            // This row is already open - close it
	            row.child.hide();
	            tr.removeClass('shown');
	        }
	        else {
	            // Open this row
	            row.child( format(dataList) ).show();
	            tr.addClass('shown');
	        }
	    } );
	} );	

	
		
	
</script>
{% endblock %}
